package com.zx.security.security;

import com.zx.untils.utils.R;
import com.zx.untils.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenLogoutHandler implements LogoutHandler {
    private TokenManger tokenManger;
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManger tokenManger, RedisTemplate redisTemplate) {
        this.tokenManger = tokenManger;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public void logout(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) {
        String token = httpServletRequest.getHeader("token");
        if (token!=null){
            String tokenInformation = tokenManger.getTokenInformation(token);
            redisTemplate.delete(tokenInformation);
        }
        ResponseUtil.out(httpServletResponse, R.ok());
    }
}
